/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.fourtwelve.client;

import edu.fourtwelve.srlzd_data.MemberData;
import edu.fourtwelve.util.BankingConstants;
import edu.fourtwelve.util.MersenneTwister;
import edu.fourtwelve.util.Utils;
import java.awt.event.WindowEvent;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author INSPIRON_ADMIN
 */
public class ClientRegistration extends javax.swing.JFrame implements BankingConstants {

    /**
     * Creates new form ClientRegistration
     */
    public ClientRegistration(final ClientLogin cLogIn, final Object WAIT_NOTIFY, final MemberData usrData) {
        this.WAIT_NOTIFY = WAIT_NOTIFY;
        this.cLogIn = cLogIn;
        this.usrData = usrData;
        
        initComponents();

        this.userNameJTextField.setText(usrData.getUsrName());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        typeButtonGroup = new javax.swing.ButtonGroup();
        firstNameJTextField = new javax.swing.JTextField();
        firstNameJLabel = new javax.swing.JLabel();
        lastNameJLabel = new javax.swing.JLabel();
        lastNameJTextField = new javax.swing.JTextField();
        addressJLabel = new javax.swing.JLabel();
        addressJTextField = new javax.swing.JTextField();
        passwordJLabel = new javax.swing.JLabel();
        passwordJPasswordField = new javax.swing.JPasswordField();
        confirmJPasswordField = new javax.swing.JPasswordField();
        confirmJLabel = new javax.swing.JLabel();
        address2JTextField = new javax.swing.JTextField();
        addrees2JLabel = new javax.swing.JLabel();
        cityJTextField = new javax.swing.JTextField();
        cityJLabel = new javax.swing.JLabel();
        stateJLabel = new javax.swing.JLabel();
        stateJTextField = new javax.swing.JTextField();
        submitJButton = new javax.swing.JButton();
        cancelJButton = new javax.swing.JButton();
        userNameJLabel = new javax.swing.JLabel();
        userNameJTextField = new javax.swing.JTextField();
        primaryAccountJTextField = new javax.swing.JTextField();
        primaryAccountJLabel = new javax.swing.JLabel();
        checkingJRadioButton = new javax.swing.JRadioButton();
        savingsJRadioButton = new javax.swing.JRadioButton();
        loanJRadioButton = new javax.swing.JRadioButton();
        typeJLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                handleClosing(evt);
            }
        });

        firstNameJLabel.setText("First Name:");

        lastNameJLabel.setText("Last Name:");

        addressJLabel.setText("Address:");

        passwordJLabel.setText("Password:");

        confirmJLabel.setText("Confirm Password:");

        addrees2JLabel.setText("Address 2:");

        cityJLabel.setText("City:");

        stateJLabel.setText("State:");

        submitJButton.setText("Submit");
        submitJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitJButtonActionPerformed(evt);
            }
        });

        cancelJButton.setText("Cancel");
        cancelJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelJButtonActionPerformed(evt);
            }
        });

        userNameJLabel.setText("User Name:");

        primaryAccountJLabel.setText("Primary Account Number:");

        typeButtonGroup.add(checkingJRadioButton);
        checkingJRadioButton.setText("Checking");

        typeButtonGroup.add(savingsJRadioButton);
        savingsJRadioButton.setText("Savings");

        typeButtonGroup.add(loanJRadioButton);
        loanJRadioButton.setText("Loan");

        typeJLabel.setText("Type:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(firstNameJLabel)
                                    .addComponent(lastNameJLabel))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lastNameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(firstNameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(17, 17, 17)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(stateJLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(stateJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cityJLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cityJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(passwordJLabel)
                                    .addComponent(userNameJLabel)
                                    .addComponent(confirmJLabel))
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(confirmJPasswordField)
                                    .addComponent(passwordJPasswordField)
                                    .addComponent(userNameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(addrees2JLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(address2JTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(submitJButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(cancelJButton))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(addressJLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(addressJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(typeJLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(checkingJRadioButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(savingsJRadioButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(loanJRadioButton))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(primaryAccountJLabel)
                                    .addGap(18, 18, 18)
                                    .addComponent(primaryAccountJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 64, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userNameJLabel)
                    .addComponent(userNameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordJLabel)
                    .addComponent(passwordJPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmJLabel)
                    .addComponent(confirmJPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(firstNameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(firstNameJLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lastNameJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lastNameJLabel))
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(primaryAccountJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(primaryAccountJLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(checkingJRadioButton)
                    .addComponent(savingsJRadioButton)
                    .addComponent(loanJRadioButton)
                    .addComponent(typeJLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addressJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addressJLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(address2JTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addrees2JLabel))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cityJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cityJLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(stateJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(stateJLabel))
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(submitJButton)
                    .addComponent(cancelJButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void submitJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitJButtonActionPerformed
        
        char[] pass = this.passwordJPasswordField.getPassword();
        char[] confirm = this.confirmJPasswordField.getPassword();

        byte[] hashedPass;
        if (validateForm() && (pass != null) && (!Arrays.equals(pass, new char[]{}))
                && pass.length > MIN_PASS_LENGTH && Arrays.equals(pass, confirm)) {
            hashedPass = hashPass();
            
            byte[] tmpSalt = new byte[20];
            byte[] tmpHashPass = new byte[hashedPass.length - 20];
            System.arraycopy(hashedPass, 0, tmpSalt, 0, 20);
            System.arraycopy(hashedPass, 20, tmpHashPass, 0, tmpHashPass.length);
            
            this.usrData.setPassword(tmpHashPass);
            this.usrData.setSalt(tmpSalt);
                        
            Arrays.fill(tmpSalt, (byte) '0');
            Arrays.fill(tmpHashPass, (byte) '0');
            
            successful = true;
        }
                
        synchronized (this.WAIT_NOTIFY) {
            finished = true;
            this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
            this.cLogIn.setVisible(true);
            this.WAIT_NOTIFY.notify();
        }
    }//GEN-LAST:event_submitJButtonActionPerformed

    private void handleClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_handleClosing
        

        synchronized (this.WAIT_NOTIFY) {
            finished = true;
            this.dispose();
            this.cLogIn.setVisible(true);
            this.WAIT_NOTIFY.notify();
        }
    }//GEN-LAST:event_handleClosing

    private void cancelJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelJButtonActionPerformed
        synchronized (this.WAIT_NOTIFY) {
            finished = true;
            this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
            this.cLogIn.setVisible(true);
            this.WAIT_NOTIFY.notify();
        }
    }//GEN-LAST:event_cancelJButtonActionPerformed

    private byte[] hashPass() {
        MessageDigest digest = null;
        final int KEY_SIZE = 64;
        byte[] salt = new byte[20];
        byte[] retVal;
        SecureRandom sr;
        try {
             sr = SecureRandom.getInstance("SHA1PRNG");
                byte[] seed = sr.generateSeed(KEY_SIZE * 4);
                
                int[] msSeed = new int[KEY_SIZE];
                for (int i = 0; i < KEY_SIZE * 4; i += 4) {
                    msSeed[i % 4] = Utils.byteArrayToInt(new byte[]{seed[i], seed[i + 1], seed[i + 2], seed[i + 3]});
                }
                MersenneTwister msRand = new MersenneTwister(msSeed);
                
                msRand.nextBytes(seed);
                sr.setSeed(seed);
                sr.nextBytes(salt);

            log.log(Level.INFO, "salt= {0}", new Object[]{Utils.toHexString(salt)});
        } catch (NoSuchAlgorithmException ex) {
            log.log(Level.SEVERE, null, ex);
        }


        try {
            digest = MessageDigest.getInstance(HASHING_FUNC);
        } catch (NoSuchAlgorithmException ex) {
            log.log(Level.SEVERE, null, ex);
        }
        char[] pass = this.passwordJPasswordField.getPassword();
        byte[] passB = new byte[pass.length];


        for (int i = 0; i < pass.length; i++) {
            passB[i] = (byte) pass[i];
        }

        digest.reset();

        digest.update(salt);

        try {
            log.log(Level.INFO, "passwordField= {0} pass= {1}",
                    new Object[]{new String(pass), new String(passB, DEFAULT_ENC)});
        } catch (UnsupportedEncodingException ex) {
            log.log(Level.SEVERE, null, ex);
        }
        byte[] tmp = digest.digest(passB);
        retVal = new byte[tmp.length + salt.length];
        
        System.arraycopy(salt, 0, retVal, 0, salt.length);
        System.arraycopy(tmp, 0, retVal, salt.length, tmp.length);
        
        Arrays.fill(passB, (byte) '0');
        Arrays.fill(pass, '0');
        Arrays.fill(tmp, (byte) '0');

        try {
            log.log(Level.INFO, "passwordField= {0} pass= {1}",
                    new Object[]{new String(pass), new String(passB, DEFAULT_ENC)});
        } catch (UnsupportedEncodingException ex) {
            log.log(Level.SEVERE, null, ex);
        }

        log.log(Level.INFO,
                "hash= {0}", new Object[]{Utils.toHexString(retVal)
                });

        return retVal;
    }

    /**
     * @param args the command line arguments
     */
    public static void showFrame(final ClientLogin cLogIn, final Object WAIT_NOTIFY, final MemberData usrData) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;




                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientRegistration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientRegistration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientRegistration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientRegistration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ClientRegistration(cLogIn, WAIT_NOTIFY, usrData).setVisible(true);
            }
        });
    }
    
    public boolean validateForm() {
        String fName = this.firstNameJTextField.getText();
        String lName = this.lastNameJTextField.getText();
        String address = this.addressJTextField.getText();
        String address2 = this.address2JTextField.getText();
        String city = this.cityJTextField.getText();
        String state = this.stateJTextField.getText();
        String accountNum = this.primaryAccountJTextField.getText();
        
        if ((fName != null) && (lName != null) && (address != null) && 
                (city != null) && (state != null) && (accountNum != null) && 
                (!(fName.equals("") || lName.equals("") || address.equals("") || 
                city.equals("") || state.equals("") || accountNum.equals("")))) {
            this.usrData.setFName(fName);
            this.usrData.setLName(lName);
            this.usrData.setAddress(address);
            this.usrData.setAddress2(address2);
            this.usrData.setCity(city);
            this.usrData.setState(state);
            this.usrData.setPrimaryAccount(accountNum);
            return true;
        }
        return false;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel addrees2JLabel;
    private javax.swing.JTextField address2JTextField;
    private javax.swing.JLabel addressJLabel;
    private javax.swing.JTextField addressJTextField;
    private javax.swing.JButton cancelJButton;
    private javax.swing.JRadioButton checkingJRadioButton;
    private javax.swing.JLabel cityJLabel;
    private javax.swing.JTextField cityJTextField;
    private javax.swing.JLabel confirmJLabel;
    private javax.swing.JPasswordField confirmJPasswordField;
    private javax.swing.JLabel firstNameJLabel;
    private javax.swing.JTextField firstNameJTextField;
    private javax.swing.JLabel lastNameJLabel;
    private javax.swing.JTextField lastNameJTextField;
    private javax.swing.JRadioButton loanJRadioButton;
    private javax.swing.JLabel passwordJLabel;
    private javax.swing.JPasswordField passwordJPasswordField;
    private javax.swing.JLabel primaryAccountJLabel;
    private javax.swing.JTextField primaryAccountJTextField;
    private javax.swing.JRadioButton savingsJRadioButton;
    private javax.swing.JLabel stateJLabel;
    private javax.swing.JTextField stateJTextField;
    private javax.swing.JButton submitJButton;
    private javax.swing.ButtonGroup typeButtonGroup;
    private javax.swing.JLabel typeJLabel;
    private javax.swing.JLabel userNameJLabel;
    private javax.swing.JTextField userNameJTextField;
    // End of variables declaration//GEN-END:variables
    //Non_Designer variables declaration
    private final Object WAIT_NOTIFY;
    private ClientLogin cLogIn;
    private MemberData usrData;
    
    public static boolean finished = false;
    public static boolean successful = false;
    private static final Logger log = Logger.getLogger(ClientRegistration.class.getName());
    // End Non_Designer variables declaration
}
